package main

import (
	"context"
	"fmt"
	"github.com/coreos/etcd/clientv3"
	"time"
)

func main() {

	var (
		config clientv3.Config
		client *clientv3.Client
		err    error
		//用于读写etcd的键值对
		kv clientv3.KV

		getResp *clientv3.GetResponse
		delResp *clientv3.DeleteResponse
	)

	config = clientv3.Config{
		Endpoints:   []string{"10.70.30.73:2379"},
		DialTimeout: 3 * time.Second,
	}

	if client, err = clientv3.New(config); err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println("hello,etcd  ")

	//统一用kv对象操作
	kv = clientv3.NewKV(client)

	//测试供批量删除数据
	//kv.Put(context.TODO(), "/cron/jobs/job2", " jobs2")
	//kv.Put(context.TODO(), "/cron/jobs/job3", " jobs3")
	//kv.Put(context.TODO(), "/cron/jobs/job4", " jobs4")

	//找到以/cron/ jobs/为prefix的所有key，返回kv s数组
	getResp, err = kv.Get(context.TODO(), "/cron/jobs/", clientv3.WithPrefix())
	if err != nil {
		fmt.Println(err)
	} else {
		//fmt.Println(getResp.Kvs)

		for _, jobs := range getResp.Kvs {

			println(string(jobs.Key), string(jobs.Value))
		}
	}

	//删除key，可以增加With相关的配置，是...

	delResp, err = kv.Delete(context.TODO(), "/cron/jobs/", clientv3.WithPrevKV(), clientv3.WithPrefix())

	if len(delResp.PrevKvs) > 0 {
		for _, kvPair := range delResp.PrevKvs {
			fmt.Println("deleted key is:", string(kvPair.Key), ",deleted values is :", string(kvPair.Value))
		}
		fmt.Println(delResp.PrevKvs)
	}
	//删除的个数
	fmt.Println(delResp.Deleted)

}
